/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sahd.broker.iONetMessageManager;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observable;
import java.util.Observer;

/**
 *
 * @author root
 */
public class IncomingNetMessageManager extends Observable implements Runnable {
    private Thread messagesReceiverThread;
    private boolean isReceivinMessages=false;

    protected boolean isIsReceivinMessages() {
        return isReceivinMessages;
    }

    private void setIsReceivinMessages(boolean isReceivinMessages) {
        this.isReceivinMessages = isReceivinMessages;
    }

    private int entryPort;
    private ServerSocket serverSocket;
    private Socket socket;
    private InputStream inputStream;
    private ObjectInputStream objectInputStream;

    protected int getEntryPort() {
        return entryPort;
    }

    protected void setEntryPort(int entryPort) {
        this.entryPort = entryPort;
    }

    protected IncomingNetMessageManager(Observer observer ,int entryPort) throws IOException{
        this.attachObserver(observer);
        this.entryPort = entryPort;
        serverSocket = new ServerSocket(entryPort);
    }
    protected void attachObserver(Observer observer){
        this.addObserver(observer);
    }

    protected void startReceivingMessages(){
        messagesReceiverThread = new Thread(this);
        messagesReceiverThread.start();
        this.setIsReceivinMessages(true);
    }

    protected void stopReceivingMessages(){
        this.setIsReceivinMessages(false);
    }

    public void run() {
        try {
            while(true){
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                objectInputStream = new ObjectInputStream(inputStream);
                this.setChanged();
                this.notifyObservers(objectInputStream.readObject());
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
